package cn.fl.yzt.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.yzt.service.IYztTrackInfoService;
import cn.fl.yzt.vo.YztTrackInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.yzt.facade.yzt.condition.YztTrackInfoQueryCondition;
import fl.yzt.facade.yzt.constant.YztTrackInfoConstant;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 一证通线索表 控制层
 */
@Controller
@RequestMapping("/yzt/yztTrackInfo")
public class YztTrackInfoController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(YztTrackInfoController.class);
	
	/**
	 * YztTrackInfo 服务层BEAN
	 */
	@Autowired
	private IYztTrackInfoService yztTrackInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载YztTrackInfo列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("yzt/yztTrackInfo/yztTrackInfoList");
        this.prepare(request,mav);
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载YztTrackInfo Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("yzt/yztTrackInfo/yztTrackInfoModify");
        //this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载YztTrackInfo Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("yzt/yztTrackInfo/yztTrackInfoModify");
		this.prepare(request,mav);
		
		String id=request.getParameter("id");
		YztTrackInfoVO yztTrackInfoVO = this.yztTrackInfoService.selectById(Long.valueOf(id));
        mav.addObject("yztTrackInfoVO", yztTrackInfoVO);
		return mav;
	}

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDtlPage.do", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView toDtlPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toDtlPage", "加载YztTrackInfo 详情页面.",CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("yzt/yztTrackInfo/yztTrackInfoDtl");
        this.prepare(request,mav);

        String id=request.getParameter("id");
        YztTrackInfoVO yztTrackInfoVO = this.yztTrackInfoService.selectById(Long.valueOf(id));
        mav.addObject("yztTrackInfoVO", yztTrackInfoVO);
        return mav;
    }
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	List<KeyValueVO> stsCdList = this.yztTrackInfoService.searchCdList(YztTrackInfoConstant.CODE_STS_CD);
        List<KeyValueVO> budgetCdList = this.yztTrackInfoService.searchCdList(YztTrackInfoConstant.CODE_BUDGET_CD);
        List<KeyValueVO> rgnPrCdList = this.yztTrackInfoService.searchRgnPrCdList();
        mav.addObject("stsCdList", JSON.toJSONString(stsCdList));
        mav.addObject("budgetCdList", JSON.toJSONString(budgetCdList));
        mav.addObject("rgnPrCdList", JSON.toJSONString(rgnPrCdList));
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initYztTrackInfoList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		YztTrackInfoQueryCondition qc = new YztTrackInfoQueryCondition();
		String cstNm = request.getParameter("cstNm");
		if (StringUtils.isNotEmpty(cstNm)) {
			qc.setCstNm(cstNm);
		}
        String cstMp = request.getParameter("cstMp");
        if (StringUtils.isNotEmpty(cstMp)) {
            qc.setCstMp(cstMp);
        }
        String rgnPrCd = request.getParameter("rgnPrCd");
        if (StringUtils.isNotEmpty(rgnPrCd)) {
            qc.setRgnPrCd(rgnPrCd);
        }
        String preferMdl = request.getParameter("preferMdl");
        if (StringUtils.isNotEmpty(preferMdl)) {
            qc.setPreferMdl(preferMdl);
        }
        String budgetCd = request.getParameter("budgetCd");
        if (StringUtils.isNotEmpty(budgetCd)) {
            qc.setBudgetCd(budgetCd);
        }
        String beginCrtTm = request.getParameter("beginCrtTm");
        if (StringUtils.isNotEmpty(beginCrtTm)) {
            qc.setBeginCrtTm(beginCrtTm);
        }
        String endCrtTm = request.getParameter("endCrtTm");
        if (StringUtils.isNotEmpty(endCrtTm)) {
            qc.setEndCrtTm(endCrtTm);
        }
        String stsCd = request.getParameter("stsCd");
        if (StringUtils.isNotEmpty(stsCd)) {
            qc.setStsCd(stsCd);
        }
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initYztTrackInfoList", "初始化YztTrackInfo列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.yztTrackInfoService.searchListPage(page);
		List<YztTrackInfoVO> list = (List<YztTrackInfoVO>) pager.getResultList();
		ListPageVO<YztTrackInfoVO> listPage = new ListPageVO<YztTrackInfoVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeYztTrackInfoByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeYztTrackInfoByIds", "删除YztTrackInfo数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.yztTrackInfoService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeYztTrackInfoByIds", "删除YztTrackInfo数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeYztTrackInfoByIds", "删除YztTrackInfo数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeYztTrackInfoByIds", "删除YztTrackInfo数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeYztTrackInfoByIds", "删除YztTrackInfo数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getYztTrackInfoById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getYztTrackInfoById", "获取YztTrackInfo数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			YztTrackInfoVO vo = this.yztTrackInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getYztTrackInfoById", "获取YztTrackInfo数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getYztTrackInfoById", "获取YztTrackInfo数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getYztTrackInfoById", "获取YztTrackInfo数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getYztTrackInfoById", "获取YztTrackInfo数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.GET,RequestMethod.POST  })
	@ResponseBody
	public void addYztTrackInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		YztTrackInfoVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForYztTrackInfo(request);//获取参数
			if(StringUtils.isBlank(entity.getCstNm())){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("姓名不能为空");
				//return result;
			}
			if(StringUtils.isBlank(entity.getCstMp())){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("手机号不能为空");
               // return result;
			}
            if(StringUtils.isBlank(entity.getRgnPrCd())){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("购车城市不能为空");
               // return result;
            }
            if(BaseConstant.IS_YESNO_YES == result.getSuccess()){
                Long id = this.yztTrackInfoService.add(entity);
                result.setData(id);
                BaseLogUtils.info(logger, "addYztTrackInfo", "新增YztTrackInfo数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addYztTrackInfo", "新增YztTrackInfo数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addYztTrackInfo", "新增YztTrackInfo数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
	    response.setContentType("text/plain");  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        Map<String, Object> map = new HashMap<String,Object>();   
        map.put("result", "content");  
        PrintWriter out;
		try {
			out = response.getWriter();
	        String resultJSON = JSON.toJSONString(result);
	        String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  
	        out.println(jsonpCallback+"("+resultJSON+")");//返回jsonp格式数据  
	        out.flush();  
	        out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}       
		// result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object modifyYztTrackInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		YztTrackInfoVO entity = null;
		try {
			entity = this.getRequestParamForYztTrackInfo(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyYztTrackInfo", "修改YztTrackInfo信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.yztTrackInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyYztTrackInfo", "修改YztTrackInfo数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyYztTrackInfo", "修改YztTrackInfo数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyYztTrackInfo", "修改YztTrackInfo数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyYztTrackInfo", "修改YztTrackInfo数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private YztTrackInfoVO getRequestParamForYztTrackInfo(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String cstNm = request.getParameter("cstNm");//客户名称
		String cstMp = request.getParameter("cstMp");//客户手机号
		String rgnPrCd = request.getParameter("rgnPrCd");//地区（省）
		String budgetCd = request.getParameter("budgetCd");//预算价款（YZT0001）
		String preferMdl = request.getParameter("preferMdl");//意向车型
		String stsCd = request.getParameter("stsCd");//线索状态（YZT0002）
		String trcRem = request.getParameter("trcRem");//备注
        String vehBd = request.getParameter("vehBd");//车辆品牌

		//验证参数并赋值
		YztTrackInfoVO entity = new YztTrackInfoVO();
 		entity.setCstNm(cstNm);//客户名称
 		entity.setCstMp(cstMp);//客户手机号
 		entity.setRgnPrCd(rgnPrCd);//地区（省）
 		entity.setBudgetCd(budgetCd);//预算价款（YZT0001）
 		entity.setPreferMdl(preferMdl);//意向车型
        if(StringUtils.isBlank(stsCd)){
            entity.setStsCd(YztTrackInfoConstant.CODE_STS_CD_1);//线索状态（YZT0002）
        }else{
            entity.setStsCd(stsCd);//线索状态（YZT0002）
        }
 		entity.setTrcRem(trcRem);//备注
        entity.setVehBd(vehBd);//车辆品牌
	
		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			if(YztTrackInfoConstant.CODE_STS_CD_3.equals(stsCd)
                    ||YztTrackInfoConstant.CODE_STS_CD_4.equals(stsCd)
                    ||YztTrackInfoConstant.CODE_STS_CD_5.equals(stsCd)){
                entity.setMdfTm(tm);
            }
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
		}
		
		return entity;
	}

    /**
     * 查询省份列表
     * @param request
     * @param response
     * @return
     * @throws BaseException
     * @throws IOException 
     */
    @RequestMapping(value = "/searchProvinceList.do", method = { RequestMethod.GET})
    @ResponseBody
    public void searchProvinceList(HttpServletRequest request, HttpServletResponse response) throws BaseException{
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"查询成功");
	    List<KeyValueVO> rgnList = this.yztTrackInfoService.searchRgnPrCdList();
	    if(CollectionUtils.isNotEmpty(rgnList)){
	        result.setData(rgnList);
        }
	    response.setContentType("text/plain");  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        Map<String, Object> map = new HashMap<String,Object>();   
        map.put("result", "content");  
        PrintWriter out;
		try {
			out = response.getWriter();
			//JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json 
			String resultJSON = JSON.toJSONString(rgnList);
			//JSONObject resultJSON = new JSONObject(rgnList);
			String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  
			out.println(jsonpCallback+"("+resultJSON+")");//返回jsonp格式数据  
			out.flush();  
			out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}       
	    //return result;
    }
}

